﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using SilverlightLoader;

namespace ZFCLoader
{

    public partial class Loader : UserControl, ISilverlightLoader
    {
        public Loader()
        {
            InitializeComponent();
        }

        #region ISilverlightLoader Members

        // called when download of all packages starts(called once)
        public void initCallback(List<Uri> packageSourceList)
        {
            m_packageSourceList = new List<Uri>(packageSourceList.Count);
            m_packageDownloadCount = packageSourceList.Count;
        }

        // called when download of each package/file starts
        public void downloadStartCallback(Uri packageSource)
        {        
            m_packageSourceList.Add(packageSource);
        }

        // called on download progress of each package/file
        public void downloadProgressCallback(Uri packageSource, DownloadProgressEventArgs eventArgs)
        {
            float percentageDownloadedAcurate = ((float)eventArgs.BytesReceived / eventArgs.TotalBytesToReceive) ;
            ProgressText.Text = (percentageDownloadedAcurate * 100).ToString("0.0") + "%";
            Trns.ScaleX = percentageDownloadedAcurate;
        }

        // called on download complete of each package/file
        public void downloadCompleteCallback(Uri packageSource, DownloadCompleteEventArgs e)
        {
            m_packageDownloadCount--;
            if (m_packageDownloadCount <= 0)
            {
                foreach (Uri source in m_packageSourceList)
                {
                    if (source.ToString().EndsWith(".xap") || source.ToString().EndsWith(".zip"))
                    {
                        EndPreloader.Completed += (s, args) => XapUtil.setCurrentXapFile(source);
                        EndPreloader.Begin();
                        break;
                    }
                }
            }
        }

        #endregion

        // data
        List<Uri> m_packageSourceList;
        int m_packageDownloadCount;
    }
}
